package com.gt.platform.task;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gt.common.WebServiceUtil;
import com.gt.common.XmlParse;
import com.gt.platform.mapper.CmdSendHisMapper;
import com.gt.platform.mapper.PlatformMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.List;
import java.util.Map;


@Slf4j
@Configuration
public class TaskService {

    @Autowired
    private CmdSendHisMapper cmdSendHisMapper;

    @Autowired
    private PlatformMapper platformMapper;

    @Scheduled(fixedDelay = 1000)
    public void handleTask() {
        List<Map<String, Object>> sendHisList = cmdSendHisMapper.cmdSendHis();
        if (sendHisList == null || sendHisList.isEmpty()) {
            return;
        }
        for (Map<String, Object> task : sendHisList) {
            String type = (String) task.get("Op_type");
            switch (type) {
                case "1":
                case "2":
                    /**1检查申请状态回写S5006(预约台)**/
                    /**2检查申请状态回写S5006(工作站)**/
                    sendApplyBill(task);
                    break;
                case "3":
                    /**回传病人危急值信息 S3103**/
                    sendCriticalValue(task);
                    break;
                case "4":
                    /**接收检查报告信息 S5008**/
                    sendCheckReport(task);
                    break;
                default:
                    log.error("发送类型错误");
            }
        }

    }
    @Scheduled(fixedDelay = 2000)
    public void handleTaskOther() {
        List<Map<String, Object>> sendHisList = cmdSendHisMapper.cmdSendHisOther();
        if (sendHisList == null || sendHisList.isEmpty()) {
            return;
        }
        for (Map<String, Object> task : sendHisList) {
            String type = (String) task.get("Op_type");
            String hisId = null;
            log.error("操作类型：==" +type);
            switch (type) {
                case "6":
                case "7":
                    /**6修改申请单状态为未执行状态**/
                    /**7是预约台回传未执行状态**/
                    sendApplyBillOther(task);
                case "8":
                    /**8是工作站保存回传执行完成状态**/
                    hisId = platformMapper.selectCheckListOne((String) task.get("send_from"));
                    if (StringUtils.isBlank(hisId)){
                        cmdSendHisMapper.recodeCmdHisOther((Integer) task.get("send_id"),"申请单id为空，看看是否是手工单");
                        cmdSendHisMapper.deleteByIdOther((Integer) task.get("send_id"));
                        log.error("8工作站保存回传执行完成状态，申请单id为空，检查表id：【{}】",(String) task.get("send_from"));
                        continue;
                    }
                    sendApplyBillOther(task);
                    break;
                case "5":
                    /**his接收取消检查报告信息 HIS_S5009**/
                    hisId = platformMapper.selectCheckListOne((String) task.get("send_from"));
                    if (StringUtils.isBlank(hisId)){
                        cmdSendHisMapper.deleteByIdOther((Integer) task.get("send_id"));
                        log.error("5his接收取消检查报告信息，申请单id为空，检查表id：【{}】",(String) task.get("send_from"));
                        continue;
                    }
                    sendCancelCheckReport(task);
                    break;
                default:
                    log.error("发送类型错误");
            }
        }

    }

    @Scheduled(fixedDelay = 120000)
    public void redoTask() {
        platformMapper.redoTask();
    }

    private void sendCriticalValue(Map<String, Object> task) {

        try {
            String checkResult = WebServiceUtil.sendData("", "ESB_PlatformSwitch");
            if (StringUtils.isBlank(checkResult)){
                log.info("【sendCriticalValue】-解密数据为null，数据为：【{}】",task.toString());
                return;
            }

            String checkData = XmlParse.parse(checkResult, "Data");
            if (!"true".equals(checkData)) {
                log.error("【sendCriticalValue】-平台服务不可用");
                return;
            }

            Integer sendId = (Integer) task.get("send_id");
            if (sendId == null){
                log.error("发送id为空，为不合法的数据，发送检查id为：【{}】",task.get("send_from").toString());
                return;
            }

            String data = createCriticalValueData(task);
            log.info("危急值数据==》：{}",data);
            String returnResult = WebServiceUtil.sendDataPost(data, "HIS_S3103");
            if (StringUtils.isBlank(checkResult)){
                log.info("【sendCriticalValue】-HIS_S3103-解密数据为null，数据为：【{}】",task.toString());
                return;
            }

            String executeStatus = executeResult(returnResult);
            if (executeStatus.equals("A")) {
                platformMapper.updateCriticalValueStatus((String) task.get("send_from"),"1","发送成功");
                cmdSendHisMapper.recodeCmdHis(sendId,"发送成功");
                cmdSendHisMapper.deleteById(sendId);
                log.info("危急值发送标记1：{}",(String) task.get("send_from"));
            } else {
                platformMapper.updateCriticalValueStatus((String) task.get("send_from"),"0",executeStatus);
                cmdSendHisMapper.recodeCmdHis(sendId,executeStatus);
                cmdSendHisMapper.deleteById(sendId);
                log.info("危急值发送标记2：{}",(String) task.get("send_from"));
            }

        } catch (Exception e) {
            platformMapper.updateCriticalValueStatus((String) task.get("send_from"),"0",e.getMessage());
            cmdSendHisMapper.recodeCmdHis((Integer) task.get("send_id"),e.getMessage());
            cmdSendHisMapper.deleteById((Integer) task.get("send_id"));
            log.info("危急值回传异常！检查表id【{}】", task.get("send_from").toString());
            e.printStackTrace();
        }
    }

    /**
     * 创建 急值数据
     *
     * @param task
     * @return
     */
    private String createCriticalValueData(Map<String, Object> task) {
        String sendId = String.valueOf(task.get("send_id"));
        String sendFrom = (String) task.get("send_from");
        String sendTo = (String) task.get("send_to");
        String criticalValueData = platformMapper.criticalValueData(sendId, sendFrom, sendTo);
        return criticalValueData;
    }

    private void sendCancelCheckReport(Map<String, Object> task) {

        try {
            String checkResult = WebServiceUtil.sendData("", "ESB_PlatformSwitch");
            if (StringUtils.isBlank(checkResult)){
                log.info("【sendCancelCheckReport】-解密数据为null，数据为：【{}】",task.toString());
                return;
            }

            String checkData = XmlParse.parse(checkResult, "Data");
            if (!"true".equals(checkData)) {
                log.error("【sendCancelCheckReport】-平台服务不可用");
                return;
            }

            Integer sendId = (Integer) task.get("send_id");
            if (sendId == null){
                log.error("发送id为空，为不合法的数据【{}】",task.toString());
                return;
            }

            Object sendFrom = task.get("send_from");
            if (sendFrom == null){
                log.error("sendFrom为空，为不合法的数据【{}】",task.toString());
                return;
            }

            Integer eXISTReport = platformMapper.selectReportStatus(task.get("send_from").toString());
            if (eXISTReport == null){
                log.error("报告还没生成，不用取消报告！");
                return;
            }

            String data = createCancelCheckReportData(task);
            String returnResult = WebServiceUtil.sendDataPost(data, "HIS_S5009");
            if (StringUtils.isBlank(returnResult)){
                log.info("【sendCancelCheckReport】-HIS_S5009-解密数据为null，数据为：【{}】",task.toString());
                return;
            }

            String executeStatus = executeResult(returnResult);
            if (executeStatus.equals("A")) {
                cmdSendHisMapper.recodeCmdHisOther(sendId,"发送成功");
                cmdSendHisMapper.deleteByIdOther(sendId);
            } else {
                cmdSendHisMapper.recodeCmdHisOther(sendId,executeStatus);
                cmdSendHisMapper.deleteByIdOther(sendId);
            }

        } catch (Exception e) {
            cmdSendHisMapper.recodeCmdHisOther((Integer) task.get("send_id"),e.getMessage());
            cmdSendHisMapper.deleteByIdOther((Integer) task.get("send_id"));
            log.error("取消检查报告信息异常！发送检查id为：【{}】", task.get("send_from").toString());
            e.printStackTrace();
        }
    }

    /**
     * 创建 取消检查报告信息
     *
     * @param task
     * @return
     */
    private String createCancelCheckReportData(Map<String, Object> task) {
        String sendId = String.valueOf(task.get("send_id"));
        String sendFrom = (String) task.get("send_from");
        String sendTo = (String) task.get("send_to");
        String cancelCheckReportData = platformMapper.cancelCheckReportData(sendId, sendFrom, sendTo);

        return cancelCheckReportData;
    }


    private void sendCheckReport(Map<String, Object> task) {

        try {
            String checkResult = WebServiceUtil.sendData("", "ESB_PlatformSwitch");
            if (StringUtils.isBlank(checkResult)){
                log.info("【sendCheckReport】-解密数据为null，数据为：【{}】",task.toString());
                return;
            }

            String checkData = XmlParse.parse(checkResult, "Data");
            if (!"true".equals(checkData)) {
                log.error("【sendCheckReport】-平台服务不可用");
                return;
            }

            Integer sendId = (Integer) task.get("send_id");
            if (sendId == null){
                log.error("发送id为空，为不合法的数据，发送检查id为：【{}】",task.get("send_from").toString());
                return;
            }

            String data = createCheckReportData(task);
            String returnResult = WebServiceUtil.sendDataPost(data, "HIS_S5008");
            if (StringUtils.isBlank(returnResult)){
                log.info("【sendCheckReport】-HIS_S5008-解密数据为null，数据为：【{}】",task.toString());
                return;
            }
            String executeStatus = executeResult(returnResult);

            if (executeStatus.equals("A")) {
                cmdSendHisMapper.recodeCmdHis(sendId,"发送成功");
                cmdSendHisMapper.deleteById(sendId);
            } else {
                cmdSendHisMapper.recodeCmdHis(sendId,executeStatus);
                cmdSendHisMapper.deleteById(sendId);
            }

        } catch (Exception e) {
            cmdSendHisMapper.recodeCmdHis((Integer) task.get("sendId"),e.getMessage());
            cmdSendHisMapper.deleteById((Integer) task.get("sendId"));
            log.error("检查报告信息异常！发送检查id为【{}】", task.get("send_from").toString());
            e.printStackTrace();
        }
    }

    private void sendCheckReport1(Map<String, Object> task) {

        try {
            String checkResult = WebServiceUtil.sendData("", "ESB_PlatformSwitch");
            if (StringUtils.isBlank(checkResult)){
                log.info("【sendCheckReport】-解密数据为null，数据为：【{}】",task.toString());
                return;
            }

            String checkData = XmlParse.parse(checkResult, "Data");
            if (!"true".equals(checkData)) {
                log.error("【sendCheckReport】-平台服务不可用");
                return;
            }

            Integer sendId = (Integer) task.get("send_id");
            if (sendId == null){
                log.error("发送id为空，为不合法的数据，发送检查id为：【{}】",task.get("send_from").toString());
                return;
            }

            String data = createCheckReportData(task);
            String returnResult = WebServiceUtil.sendDataPost(data, "HIS_S5008");
            if (StringUtils.isBlank(returnResult)){
                log.info("【sendCheckReport】-HIS_S5008-解密数据为null，数据为：【{}】",task.toString());
                return;
            }
            String executeStatus = executeResult(returnResult);

            if (executeStatus.equals("A")) {
                cmdSendHisMapper.recodeCmdHis(sendId,"发送成功");
                cmdSendHisMapper.deleteById(sendId);
            } else {
                cmdSendHisMapper.recodeCmdHis(sendId,executeStatus);
                cmdSendHisMapper.deleteById(sendId);
            }

        } catch (Exception e) {
            cmdSendHisMapper.recodeCmdHis((Integer) task.get("sendId"),e.getMessage());
            cmdSendHisMapper.deleteById((Integer) task.get("sendId"));
            log.error("检查报告信息异常！发送检查id为【{}】", task.get("send_from").toString());
            e.printStackTrace();
        }
    }


    /**
     * 创建 检查报告信息
     *
     * @param task
     * @return
     */
    private String createCheckReportData(Map<String, Object> task) {
        String sendId = String.valueOf(task.get("send_id"));
        String sendFrom = (String) task.get("send_from");
        String sendTo = (String) task.get("send_to");
        String checkReportData = platformMapper.checkReportData(sendId, sendFrom, sendTo);
        return checkReportData;
    }

    private void sendApplyBill(Map<String, Object> task) {

        try {
            String checkResult = WebServiceUtil.sendData("", "ESB_PlatformSwitch");
            if (StringUtils.isBlank(checkResult)){
                log.info("【sendApplyBill】-解密数据为null，数据为：【{}】",task.toString());
                return;
            }

            String checkData = XmlParse.parse(checkResult, "Data");
            if (!"true".equals(checkData)) {
                log.error("【sendApplyBill】-平台服务不可用");
                return;
            }

            Integer sendId = (Integer) task.get("send_id");
            if (sendId == null){
                log.error("发送id为空，为不合法的数据，申请单号为：【{}】",task.get("send_from").toString());
                return;
            }

            String data = createApplyBillData(task);
            String returnResult = WebServiceUtil.sendData(data, "HIS_S5006");
            if (StringUtils.isBlank(returnResult)){
                log.info("【sendApplyBill】-HIS_S5006-解密数据为null，数据为：【{}】",task.toString());
                return;
            }

            String executeStatus = executeResult(returnResult);
            if (executeStatus.equals("A")) {
                cmdSendHisMapper.recodeCmdHis(sendId,"发送成功");
                cmdSendHisMapper.deleteById(sendId);
            } else {
                cmdSendHisMapper.recodeCmdHis(sendId,executeStatus);
                cmdSendHisMapper.deleteById(sendId);
            }

        } catch (Exception e) {
            cmdSendHisMapper.recodeCmdHis((Integer) task.get("send_id"),e.getMessage());
            cmdSendHisMapper.deleteById((Integer) task.get("send_id"));
            log.error("回传申请单异常！发送id【{}】", task.get("send_from").toString());
            e.printStackTrace();

        }
    }

    private String createApplyBillData(Map<String, Object> task) {
        String sendId = String.valueOf(task.get("send_id"));
        String sendFrom = (String) task.get("send_from");
        String sendTo = (String) task.get("send_to");
        String opType = (String) task.get("Op_type");
        String applyBillData = platformMapper.createApplyBillData(sendId, sendFrom, sendTo,opType);

        return applyBillData;
    }


    /**
     * 处理执行结果
     **/
    private String executeResult(String returnResult) throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode rootNode = objectMapper.readTree(returnResult);
        JsonNode input = rootNode.get("input");
        JsonNode ackInfo = input.get("ack_info");
        String exeStatus = ackInfo.get("exe_status").toString();
        exeStatus = exeStatus.replaceAll("^\"|\"$", "");
        if (exeStatus.equals("E")) {
            String errMsg = ackInfo.get("err_msg").toString();
            errMsg = errMsg.replaceFirst("^\"", "").replaceFirst("\"$", "");
            log.error("平台返回错误信息{}", errMsg);
            return errMsg;
        }
        return exeStatus;
    }

    private void sendApplyBillOther(Map<String, Object> task) {

        try {
            String checkResult = WebServiceUtil.sendData("", "ESB_PlatformSwitch");
            if (StringUtils.isBlank(checkResult)){
                log.info("【sendApplyBill】-解密数据为null，数据为：【{}】",task.toString());
                return;
            }

            String checkData = XmlParse.parse(checkResult, "Data");
            if (!"true".equals(checkData)) {
                log.error("【sendApplyBill】-平台服务不可用");
                return;
            }

            Integer sendId = (Integer) task.get("send_id");
            if (sendId == null){
                log.error("发送id为空，为不合法的数据，申请单号为：【{}】",task.get("send_from").toString());
                return;
            }

            String data = createApplyBillData(task);
            String returnResult = WebServiceUtil.sendData(data, "HIS_S5006");
            if (StringUtils.isBlank(returnResult)){
                log.info("【sendApplyBill】-HIS_S5006-解密数据为null，数据为：【{}】",task.toString());
                return;
            }

            String executeStatus = executeResult(returnResult);
            if (executeStatus.equals("A")) {
                cmdSendHisMapper.recodeCmdHisOther(sendId,"发送成功");
                cmdSendHisMapper.deleteByIdOther(sendId);
                cmdSendHisMapper.updateSendFlag(task.get("send_from").toString(),"1");
            } else {
                cmdSendHisMapper.recodeCmdHisOther(sendId,executeStatus);
                cmdSendHisMapper.deleteByIdOther(sendId);
                cmdSendHisMapper.updateSendFlag(task.get("send_from").toString(),"0");
            }

        } catch (Exception e) {
            cmdSendHisMapper.recodeCmdHisOther((Integer) task.get("send_id"),e.getMessage());
            cmdSendHisMapper.deleteByIdOther((Integer) task.get("send_id"));
            cmdSendHisMapper.updateSendFlag(task.get("send_from").toString(),"0");
            log.error("回传申请单异常！发送id【{}】", task.get("send_from").toString());
            e.printStackTrace();

        }
    }

    /**
     * 每分钟检查是否有发送失败3次以上的数据
     */
//    @Scheduled(fixedDelay = 60000)
//    public void deleteTask(){
//
//        List<Map<String, Object>> sendHisList = cmdSendHisMapper.cmdSendHisDelete();
//        if (sendHisList == null || sendHisList.isEmpty()) {
//            return;
//        }
//        for (Map<String, Object> task : sendHisList) {
//            Integer sendId = (Integer) task.get("send_id");
//            if (sendId == null){
//                return;
//            }
//            cmdSendHisMapper.recodeCmdHisError(sendId);
//            cmdSendHisMapper.deleteById(sendId);
//        }
//
//    }
//    private void sendCancelFee(Map<String, Object> task) {
//        try {
//            String checkResult = WebServiceUtil.sendData("", "ESB_PlatformSwitch");
//            if (StringUtils.isBlank(checkResult)){
//                log.info("【sendCancelFee】-解密数据为null，数据为：【{}】",task.toString());
//                return;
//            }
//
//            String checkData = XmlParse.parse(checkResult, "Data");
//            if (!"true".equals(checkData)) {
//                log.error("【sendCancelFee】-平台服务不可用");
//                return;
//            }
//
//            Integer sendId = (Integer) task.get("send_id");
//            if (sendId == null){
//                log.error("发送id为空，为不合法的数据，发送检查id为：【{}】",task.get("send_from").toString());
//                return;
//            }
//
//            String data = createCancelFeeData(task);
//            String returnResult = WebServiceUtil.sendDataPost(data, "HIS_S3122");
//            if (StringUtils.isBlank(checkResult)){
//                log.info("【sendCancelFee】-HIS_S3122-解密数据为null，数据为：【{}】",task.toString());
//                return;
//            }
//
//            String executeStatus = executeResult(returnResult);
//            if (executeStatus.equals("A")) {
//                cmdSendHisMapper.recodeCmdHis(sendId,"发送成功");
//                cmdSendHisMapper.deleteById(sendId);
//                platformMapper.cancelFree(task.get("send_from").toString());
//            } else {
//                cmdSendHisMapper.recodeCmdHis(sendId,executeStatus);
//                cmdSendHisMapper.deleteById(sendId);
//            }
//
//        } catch (Exception e) {
//            cmdSendHisMapper.recodeCmdHis((Integer) task.get("send_id"),e.getMessage());
//            cmdSendHisMapper.deleteById((Integer) task.get("send_id"));
//            log.error("取消费用回传异常！检查表id【{}】", task.get("send_from").toString());
//            e.printStackTrace();
//        }
//    }
//
//    /**
//     * 创建取消费用信息
//     * @param task
//     * @return
//     */
//    private String createCancelFeeData(Map<String, Object> task) {
//        String sendId = String.valueOf(task.get("send_id"));
//        String sendFrom = (String) task.get("send_from");
//        String sendTo = (String) task.get("send_to");
//        String cancelFeeData = platformMapper.cancelFeeData(sendId, sendFrom, sendTo);
//        return cancelFeeData;
//    }
}
